<template>
  <section class="todoapp">
    <!-- 头部部分 -->
    <Headers @addList="addList"></Headers>
    <!-- 主体部分 -->
    <Body
      :list="renderList"
      @changeStaus="changeStaus"
      @delList="delList"
      :small="small"
      @changeAll="changeAll"
    ></Body>
    <!-- 底部部分 -->
    <Footer
      :outList="outList"
      @clearIsDone="clearIsDone"
      :showClrea="showClrea"
      v-if="list.length"
      :type="type"
      @changecolor="changecolor"
    ></Footer>
  </section>
</template>

<script>
import Headers from '@/components/Header.vue'
import Body from '@/components/Body.vue'
import Footer from '@/components/Footer.vue'
export default {
  components: {
    Headers,
    Body,
    Footer
  },
  data () {
    return {
      type: 'all',
      list: JSON.parse(localStorage.getItem('TodoList')) || []
    }
  },
  methods: {
    changeStaus (id) {
      const res = this.list.find(item => item.id === id)
      res.isDone = !res.isDone
    },
    //删除功能
    delList (id) {
      this.list = this.list.filter(item => item.id !== id)
    },
    clearIsDone () {
      this.list = this.list.filter(item => item.isDone === false)
    },
    changecolor (type) {
      this.type = type
    },
    addList (value) {
      const obj = { id: +new Date(), name: value, isDone: false }
      this.list = [obj, ...this.list]
    },
    changeAll (bl) {
      this.list.forEach(item => (item.isDone = bl))
    }
  },
  computed: {
    outList () {
      return this.list.filter(item => item.isDone === false).length
    },
    showClrea () {
      return this.list.some(item => item.isDone)
    },
    //全选反选
    small () {
      return this.list.every(item => item.isDone)
    },
    renderList () {
      switch (this.type) {
        case 'all':
          return this.list
        case 'active':
          return this.list.filter(item => item.isDone === false)
        case 'completed':
          return this.list.filter(item => item.isDone === true)

        default:
          return this.list
      }
    }
  },
  watch: {
    list: {
      deep: true,
      immediate: true,
      handler (newValue) {
        localStorage.setItem('TodoList', JSON.stringify(newValue))
      }
    }
  }
}
</script>

<style></style>
